
export default class Collector{

    static __instance = null;
    static instance = function() {
        if (Collector.__instance == null) {
            Collector.__instance = new Collector();
        }
        return Collector.__instance;
    };
    static defaultStyle = {
        image: '',
        verticalOrigin: Cesium.VerticalOrigin.BASELINE
    }

    constructor() {
        this._viewer = window.cesiumViewer;
        this._timeout = null;
        this._handler = null;
        this._marker = null;
        //this._downPosition = nu;;
    }

    init(){
        this.handler = new Cesium.ScreenSpaceEventHandler(this._viewer.canvas);
        let self = this;
        let downpos = null;
        function pressfun(e){
            if(self._timeout){
                window.clearTimeout(self._timeout);
            }
            downpos = e.position;
            self._timeout = setTimeout(function () {
                self.pick(e)
            },600);
        }
        function unpressfun(e){
            if(!self._timeout){return;}
            let cancel = true;
            if(downpos && e.endPosition && Cesium.Cartesian2.distanceSquared(downpos,e.endPosition) < 20){
                cancel = false
            }
            if(cancel){
                window.clearTimeout(self._timeout);
                self._timeout = null;
                downpos = null;
            }
        }
        this.handler.setInputAction(pressfun, Cesium.ScreenSpaceEventType.LEFT_DOWN);
        this.handler.setInputAction(unpressfun, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        this.handler.setInputAction(unpressfun, Cesium.ScreenSpaceEventType.LEFT_UP);
    }

    pick(e){
        let point = window.cesiumPickPosition(e.position);
        const evt = new CustomEvent('EVENT_COLLECTOR_PICKED', {
            detail: {
                position:point
            }
        })
        window.dispatchEvent(evt);

        this._marker = this._viewer.entities.add({
            name: '标点',
            position: point,
            billboard:{
                image: Collector.defaultStyle.image,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                scale: 1,
            }
        });
    }

    clear(){
        if(this._marker){
            this._viewer.entities.remove(this._marker);
            this._marker = null;
        }
    }





}